import React from "react";
import './TodoMain.css';
import {useSelector, useDispatch} from 'react-redux';
import { checkTodo, asyncReqRemoveTodo, asyncReqCheckTodo } from "../../redux-n/slices/todoSlice";

export default function TodoMain() {
  //获取redux中的 todo 状态值
  let todos = useSelector(state => state.todos);
  //获取 dispatch 函数
  let dispatch = useDispatch();
  //修改状态
  let check = (id) => {
    return (e) => {
      //修改当前任务的状态
      dispatch(asyncReqCheckTodo({id: id, done: e.target.checked}))
    }
  }

  //删除事件
  let remove = (id) => {
    return () => {
      dispatch(asyncReqRemoveTodo(id));
    }
  }
  return (
    <ul className="todo-main">
      {
        todos.map(item => {
          return <li key={item.id}>
                  <label>
                    <input 
                      type="checkbox" 
                      checked={item.done} 
                      onChange={check(item.id)}  
                    />
                    <span>{item.title}</span>
                  </label>
                  <button 
                    className="btn btn-danger"
                    onClick={remove(item.id)}
                    >删除</button>
                </li>
        })
      }
    </ul>
  );
}
